/**
 * 
 */
package com.ibuonline.search.solr.loader;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 产品竞价数据加载器
 * 
 * @author Liuye
 * 
 */
public class ProductElevationLoader extends AbstractDbFileLoader implements
		DataLoader {
	private static final Logger log = LoggerFactory
			.getLogger(ProductElevationLoader.class);
	private static final String encode = "UTF-8";
	private String sql = "SELECT keyword,prod_id AS product_id FROM prod_paid_ranking"
			+ " WHERE DATEDIFF(CURRENT_DATE(),effective_time)>=0 AND DATEDIFF(expire_time,CURRENT_DATE())>=0"
			+ " ORDER BY keyword,bid_price DESC";

	@Override
	protected void proecessResultSet(ResultSet rs) throws SQLException {
		Map<String, List<Long>> map = new LinkedHashMap<String, List<Long>>();
		while (rs.next()) {
			String keyword = rs.getString("keyword");
			List<Long> list = map.get(keyword);
			if (list == null) {
				list = new ArrayList<Long>();
				map.put(keyword, list);
			}
			list.add(rs.getLong("product_id"));
		}
		saveDocument(map);
	}

	protected void saveDocument(Map<String, List<Long>> map) {
		Document doc = DocumentHelper.createDocument();
		doc.setXMLEncoding(encode);

		// 创建根元素
		Element rootElement = DocumentHelper.createElement("elevate");
		doc.setRootElement(rootElement);
		for (Map.Entry<String, List<Long>> entry : map.entrySet()) {
			// query节点对象
			Element queryElement = rootElement.addElement("query");
			queryElement.addAttribute("text", entry.getKey());
			// 创建doc子节点对象
			for (Long companyId : entry.getValue()) {
				Element docElement = queryElement.addElement("doc");
				docElement.addAttribute("id", String.valueOf(companyId));
			}
		}

		// xml写入临时文件
		File tempPath = new File(tempDir);
		if (!tempPath.exists()) {
			tempPath.mkdirs();
		}
		File tempFile = new File(tempPath, UUID.randomUUID().toString()
				+ ".xml");
		FileOutputStream fs;
		try {
			fs = new FileOutputStream(tempFile);
			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding(encode); // 指定XML编码
			XMLWriter output = new XMLWriter(fs, format);
			output.write(doc);
			output.close();

			// 复制临时文件到目标文件
			FileUtils.copyFile(tempFile, new File(outFile));
		} catch (IOException e) {
			log.error("IO异常。", e);
		} finally {
			// 删除临时文件
			if (tempFile.exists()) {
				try {
					FileUtils.forceDelete(tempFile);
				} catch (IOException e) {
				}
			}
		}

	}

	@Override
	protected String getSql() {
		return sql;
	}

	@Override
	protected String getJobName() {
		return "产品竞价排名";
	}
}
